package com.JobWebGem.system.controller;

import com.JobWebGem.system.common.BaseResponse;
import com.JobWebGem.system.common.DeleteRequest;
import com.JobWebGem.system.common.ErrorCode;
import com.JobWebGem.system.common.ResultUtils;
import com.JobWebGem.system.exception.BusinessException;
import com.JobWebGem.system.exception.ThrowUtils;
import com.JobWebGem.system.model.dto.delivery.DeliveryAddRequest;
import com.JobWebGem.system.model.dto.delivery.DeliveryQueryRequest;
import com.JobWebGem.system.model.dto.delivery.StatusChangeRequest;
import com.JobWebGem.system.model.entity.Delivery;
import com.JobWebGem.system.model.entity.Hr;
import com.JobWebGem.system.model.entity.Job;
import com.JobWebGem.system.model.vo.DeliveryVO;
import com.JobWebGem.system.service.DeliveryService;
import com.JobWebGem.system.service.HrService;
import com.JobWebGem.system.service.JobService;
import com.JobWebGem.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 简历投递接口
 *
 * @author renli
 */
@RestController
@RequestMapping("/delivery")
@Slf4j
@Api(tags = "简历投递接口")
public class DeliveryController {

    @Resource
    private UserService userService;

    @Resource
    private DeliveryService deliveryService;

    @Resource
    private JobService jobService;

    @Resource
    private HrService hrService;

    // region 增删改查

    /**
     * 创建简历投递
     *
     * @param deliveryAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("创建简历投递")
    public BaseResponse<Integer> addDelivery(@RequestBody DeliveryAddRequest deliveryAddRequest,
            HttpServletRequest request) {
        if (deliveryAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Integer id = userService.getLoginUser(request).getId();

        Delivery delivery = new Delivery();
        QueryWrapper<Job> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", deliveryAddRequest.getJobId());
        Job job = jobService.getOne(queryWrapper);
        BeanUtils.copyProperties(deliveryAddRequest, delivery);
        delivery.setUserId(id);
        delivery.setCompanyId(job.getCompanyId());
        delivery.setStatus("待处理");
        delivery.setDeliveryTime(new Date());
        boolean result = deliveryService.save(delivery);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "简历投递失败");
        return ResultUtils.success(delivery.getId());
    }

    /**
     * 删除简历投递记录
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation("删除简历投递记录")
    public BaseResponse<Boolean> deleteDelivery(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        boolean result = deliveryService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除简历投递记录失败");
        return ResultUtils.success(result);
    }

    /**
     * 获取用户所有的投递记录
     *
     * @return Page<Job>
     */
    @PostMapping("/list/page/my")
    @ApiOperation("获取用户所有的投递记录（仅用户）")
    public BaseResponse<Page<DeliveryVO>> listDeliveryByMy(@RequestBody DeliveryQueryRequest deliveryQueryRequest,
            HttpServletRequest request) {
        long current = deliveryQueryRequest.getCurrent() == 0 ? 1 : deliveryQueryRequest.getCurrent();
        long pageSize = deliveryQueryRequest.getPageSize() == 0 ? 10 : deliveryQueryRequest.getPageSize();

        Integer userId = userService.getLoginUser(request).getId();
        Page<DeliveryVO> paramPage = new Page<>(current, pageSize);

        Page<DeliveryVO> businessList = deliveryService.listPage(paramPage, deliveryQueryRequest, userId);

        return ResultUtils.success(businessList);
    }

    /**
     * 获取公司收到的所有投递记录
     *
     * @return Page<Job>
     */
    @PostMapping("/list/page/company")
    @ApiOperation("获取公司收到的所有投递记录(仅hr)")
    public BaseResponse<Page<DeliveryVO>> listDeliveryByCompany(@RequestBody DeliveryQueryRequest deliveryQueryRequest,
            HttpServletRequest request) {
        long current = deliveryQueryRequest.getCurrent() == 0 ? 1 : deliveryQueryRequest.getCurrent();
        long pageSize = deliveryQueryRequest.getPageSize() == 0 ? 10 : deliveryQueryRequest.getPageSize();
        Integer userId = userService.getLoginUser(request).getId();
        QueryWrapper<Hr> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        Hr hr = hrService.getOne(queryWrapper);
        Integer companyId = hr.getCompanyId();
        Page<DeliveryVO> paramPage = new Page<>(current, pageSize);

        Page<DeliveryVO> businessList = deliveryService.listPageByCompany(paramPage, deliveryQueryRequest, companyId);

        return ResultUtils.success(businessList);
    }

    /**
     * hr修改投递状态
     *
     * @return Page<Job>
     */
    @PostMapping("/change/status")
    @ApiOperation("hr修改投递状态")
    public BaseResponse<Boolean> listDeliveryByCompany(@RequestBody StatusChangeRequest statusChangeRequest,
            HttpServletRequest request) {
        if (statusChangeRequest == null || statusChangeRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Delivery delivery;
        QueryWrapper<Delivery> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", statusChangeRequest.getId());
        delivery = deliveryService.getOne(queryWrapper);
        delivery.setStatus(statusChangeRequest.getStatus());
        delivery.setResponse(statusChangeRequest.getResponse());

        boolean result = deliveryService.updateById(delivery);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "修改投递状态失败");
        return ResultUtils.success(result);
    }
    // endregion

}
